<template>
	<skeleton :skeleton="{name:'examsub'}" :showSkeleton="showSkeleton">
		<block slot="content">
			<no-data :showErrorTip="noData">
				<view slot="content" class="container">
					<water-mark :meta="meta"></water-mark>
					<view class="not-btn">
					<!-- 	<view>{{timeTmp}}</view>
						<button @click="answerSheet">答题卡</button> -->
						<question :subject="curSubject" :subjectSize="subjectSize" @change="change"></question>
					</view>
					<view class="btn">
						<view class="btn-left" @click="previousQuestion()">
							<text class="btn-textl">上一题</text>
						</view>
						<view v-if="!isLast" class="btn-right" @click="nextQuestion()">
							<text class="btn-text">下一题</text>
						</view>
						<view v-if="isLast" class="btn-right" @click="submitExam()">
							<text class="btn-text">提交</text>
						</view>
					</view>
				</view>
			</no-data>
		</block>
	</skeleton>
</template>

<script>
	import {isEmpty} from '@/utils/index';
	import Question from './fragments/Question';
	import navbarExam from '@/mixins/common/navbar/exam';
	import timeMixin from '@/mixins/exam/timeMixin';
	import examCommon from '@/mixins/exam/examCommon';
	import mixins from '@/mixins/index';
	import {
		mapState,
		mapGetters,
		mapMutations,
		mapActions
	} from 'vuex';
	export default {
		components: {
			Question
		},
		mixins: [mixins,navbarExam, timeMixin,examCommon],
		data() {
			return {
				countDownObj:undefined,
				showSkeleton: true,
				noData: false,
				examBarData: [{
						img: '/static/exam/examBar02.png',
						text: '收藏',
						id: 'collect',
						type: 'static',
						onPress: (context) => {
							context.collectSubject()
						}
					},
					{
						img: '/static/exam/examBar03.png',
						text: '答题卡',
						id: 'card',
						type: 'static',
						onPress: (context) => {
							uni.navigateTo({
								url: "/pages/exam/answerSheet"
							})
						}
					},
					{
						img: '/static/exam/examBar04.png',
						text: '00:00:00',
						type: 'dynamics',
						id: 'time',
						onPress: (context) => {
						}
					}
				]
			}
		},
		computed: {
			...mapState({
				curIndex: state => state.examStore.curIndex,
				curSubject: state => state.examStore.curSubject,
				subjectSize: state => state.examStore.examData == undefined ? 0 : state.examStore.examData.subjectSize,
				param:state => state.examStore.param
			}),
			//是否是最后一题
			isLast() {
				return this.curIndex+1 == this.subjectSize
			},
			//是否是第一题
			isFirst() {
				return this.curIndex == 0;
			}
		},
		watch:{
			curIndex:function (newValue) {
				console.log('reDrawCollect');
				this.reDrawCollect(this);
				this.reset();
			}
		},
		onLoad(query) {
			this.setAscriptionPage({
				ascriptionPage:query.ascription
			});
			//再来一套
			uni.$on('onOnceAgain',(payload)=>{
				this.loadData();
			});
			//答题卡页面操作，时间做相应的处理
			uni.$on('onSheet',(payload)=>{
				const{optionType} = payload;
				// console.log('onSheet',JSON.stringify(payload));
				if('submit'==optionType){
					// console.log('stop');
					this.saveSingleTime() //保存单题时间
					this.stop();//停止计时
					//清除倒计时
					if(!isEmpty(this.countDownObj)){
						clearTimeout(this.countDownObj);
					}
					const usedTime = this.totalTime();
					this.updateUsedTime(usedTime);//共享总用时
				}else if('clickIndex'==optionType){
					// console.log('saveSingleTime');
					this.saveSingleTime() //保存单题时间
				}
			});
			this.initParam(query);
			this.loadData();
		},
		onUnload() {
			//清除倒计时
			if(!isEmpty(this.countDownObj)){
				clearTimeout(this.countDownObj);
			}
			this.resetExamStore();
			uni.$off('onSheet');
			uni.$off('onOnceAgain');
		},
		onBackPress(options) {
			if (options.from === 'navigateBack') {
				return false;
			} 
			if(this.noData||this.showSkeleton){
				uni.navigateBack({
					delta:1
				})
				return false;
			}
			if (this.param.examType == 6||this.param.examType == 7||this.param.examType == 8) { //模拟考试不能返回
				uni.showToast({
					title: "模拟考试不能中途退出",
					icon: "none",
					duration: 2000
				})
				return true;
			}
			let self = this;
			uni.showModal({
				content: "确定要退出练习？退出后未完成的练习可在‘历史答题’记录中继续完成",
				success: function(res) {
					if (res.confirm) {
						let callback = (response) => {
							uni.showToast({
								title: response.message,
								icon: "none",
								duration: 2000
							})
							const examType = self.param.examType;
							if (examType == 4 || examType == 5 || examType == 6) {
								uni.navigateBack({
									delta: 1
								})
							} else {
								uni.switchTab({
									url: '/pages/tabbar/home/index'
								});
							}
						}
						self.saveExam(false,1,callback);
					}
				}
			});
			return true;
		},
		methods: {
			...mapMutations({
				updateIndex: 'examStore/updateIndex',
				updateUsedTime: 'examStore/updateUsedTime',
				initParam: 'examStore/initParam',
				increaseIndex: 'examStore/increaseIndex',
				decreaseIndex: 'examStore/decreaseIndex',
				updateSubjectChoice: 'examStore/updateSubjectChoice',
				resetExamStore:'examStore/resetExamStore',
				setAscriptionPage:'msgStore/setAscriptionPage'
			}),
			...mapActions({
				getExam: 'examStore/getExam',
				saveExamResult: 'examStore/saveExamResult',
			}),
			answerSheet(){
				uni.navigateTo({
					url:'/pages/exam/answerSheet'
				})
			},
			//请求试题数据
			loadData() {
				let callback = (response) => {
					const {
						success,
						code,
						message,
					} = response;
					const quitSecond = response.result.quitSecond;
					this.showSkeleton = false;
					if (success) {
						if (code == 202) { //未获取到试题
							this.noData = true
						} else if (code == 201) { //系统题库不足，只展示现有题目数量
							uni.showModal({
								content:message,
								showCancel:false
							})
						}
						this.start() //单题计时
						this.startTime = new Date().getTime();
						this.countDown(quitSecond);
					} else {
						this.noData = true
					}
				};
				this.getExam({
					callback: callback
				});
			},
			//保存做题结果
			saveExam(isForceSubmit,isFinished, callback) {
				// this.stop();
				//清除倒计时
				if(!isEmpty(this.countDownObj)){
					clearTimeout(this.countDownObj);
				}
				// const usedTime = this.totalTime();
				// this.updateUsedTime(usedTime);
				this.saveExamResult({
					isForceSubmit:isForceSubmit,
					isFinished: isFinished,
					callback: callback
				});
			},
			//模拟大赛，交卷倒计时
			countDown(time){
				// console.log('倒计时')
				if(this.param.examType==6){
					console.log('交卷倒计时',time);
					if(isEmpty(time)||time<=0){
						uni.showModal({
							content:"考试时间已经结束,无法答题",
							showCancel:false,
							confirmText:"确定",
							success(res) {
								if(res.confirm){
									uni.$emit('examFinish')
									uni.navigateBack();
								}
							}
						})
						return;
					}
					// time = 1;
					let self = this;
					this.countDownObj = setTimeout(function(){
						uni.showModal({
							content:"已到交卷时间，不能继续答题，请确认交卷，5分钟有效，超时无法交卷",
							showCancel:false,
							confirmText:"提交",
							success(res) {
								if(res.confirm){
									self.submitExam(true);
								}
							}
						})
					},time*1000);
				}
			},
			//用户选择选项
			change(value) {
				this.updateSubjectChoice(value);
			},
			//下一题
			nextQuestion() {
				let callback = () => {
					this.saveSingleTime() //保存单题时间
					this.updateIndex(this.curIndex + 1); //this.dataIndex++
					// this.reset();
				}
				if (isEmpty(this.curSubject.selectChoice)||this.curSubject.selectChoice.length == 0) {
					const content = "您还没有选择答案,确定要进入下一题吗？"
					uni.showModal({
						content: content,
						success: (res) => {
							if (res.confirm) {
								callback();
							}
						}
					})
				} else {
					callback();
				}
			},
			//上一题
			previousQuestion() {
				if (this.isFirst) {
					uni.showToast({
						title: "已经是第一题了",
						icon: "none",
						duration: 2000
					})
				} else {
					this.saveSingleTime(); //保存单题计时
					this.updateIndex(this.curIndex - 1);
					// this.reset(); //重新开始计时
				}
			},
			
			//提交
			submitExam(isForce) {
				let callback = (response) => {
					if (response.success) {
						if ("0" == response.result.isShowResult) { //0:立即显示，1：暂不展示
							uni.redirectTo({
								url: '/pages/exam/result?delta=1'+
									'&recordId=' + response.result.recordId
							})
						} else {
							uni.redirectTo({
								url:"/pages/exam/submit"
							})
						}
					}else{
						uni.showToast({
							title:response.message,
							icon:"none",
							duration:2000
						})
					}
				}
				const forceSubmit = isEmpty(isEmpty)?false:isForce;
				this.saveExam(forceSubmit,2,callback);			
			},
			showModel(mes) {
				if (mes != undefined) {
					uni.showModal({
						title: '提示',
						content: mes
					});
				}
			},
		}
	}
</script>

<style lang='scss' scoped>
	.container {
		height: 100%;
		background: #fff;
	}

	.head {
		position: relative;
		height: 100upx;
		line-height: 100upx;
		margin: 0 20upx;

		&-left {
			position: absolute;
			width: 75%;
			left: 0;
			display: flex;
		}

		&-right {
			position: absolute;
			display: inline-block;
			right: 0;
			vertical-align: middle;
			width: 20%;
			text-align: right;
		}

		&-text {
			width: 30%;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			font-size: 30upx;
			color: #5ea1f8;
			font-weight: bold;
			display: inline-block;
		}



		&-textype {
			font-size: 24upx;
			color: #666;
			position: relative;
			padding-left: 36upx;

			.head-img {
				width: 24upx;
				height: 28upx;
				display: inline-block;
				position: absolute;
				top: 36upx;
				left: 0;
			}
		}

		&-i {
			display: inline-block;
			margin-right: 50upx;
		}

		&-ico {
			margin-top: 20upx;
			display: inline-block;
			width: 40upx;
			height: 40upx;
			text-align: center;
			background: #999;
			border-radius: 50%;
			color: #fff;
		}

		&-num {
			display: inline-block;
			color: #5ea1f8;
			font-size: 24upx;
		}
	}

	.line {
		width: 100%;
		height: 1upx;
		border-bottom: 1upx solid #eee;
	}

	.sure-btn {
		display: inline-block;
		width: 100upx;
		height: 60upx;
		line-height: 60upx;
		text-align: center;
		background-color: #5ea1f8;
		border-radius: 8upx;
		font-size: 28upx;
		color: #ffffff;
	}

	.not-btn {
		margin-bottom: 90upx;
	}

	.btn {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		text-align: center;
		line-height: 80upx;

		&-left {
			display: inline-block;
			width: 50%;
			height: 80upx;
			background: #fff;
			box-shadow: 0 -1upx 10upx #ccc;
		}

		&-right {
			display: inline-block;
			width: 50%;
			height: 80upx;
			background: #5ea1f8;
			box-shadow: 0 -1upx 10upx #ccc;
		}

		&-textl {
			font-size: 28upx;
			color: #333;
		}

		&-text {
			font-size: 28upx;
			color: #fff;
		}
	}

	.show {
		display: block;
	}

	.hide {
		display: none;
	}
</style>

<style lang='scss'>
	page {
		height: 100%;
	}
</style>
